package cn.edu.pku.ss.situationawareperceiver;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class RelationHandler extends DefaultHandler{
	
	private Relation relation;
	private List<Relation> relations;
	
	private final int SITUATIONID = 1;
	private int currentState = 0;
	
	public RelationHandler()
	{
		relations = new ArrayList<Relation>();
	}
	
	public List<Relation> getRelations()
	{
		return relations;
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if(localName.equals("relation"))
		{
			relation = new Relation();
			return;
		}
		if(localName.equals("situationID"))
		{
			currentState = SITUATIONID;
			return;
		}
	}
	
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
		String content = new String(ch, start, length);
		switch(currentState)
		{
		case SITUATIONID:
			String[] items = content.split(",");
			relation.setPrevious(Integer.parseInt(items[0]));
			relation.setNext(Integer.parseInt(items[1]));
			currentState = 0;
			break;
		default:
			break;
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		if(localName.equals("relation"))
		{
			relations.add(relation);
			return;
		}
	}
}
